//
//  JrdChapterNodeViewController.m
//  iMandarin
//
//  Created by longcheng on 16/8/6.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdChapterNodeViewController.h"
#import "JrdCommon.h"
#import "CKHttpCommunicate.h"
#import "MJRefresh.h"
#import "JZCourseDetailModel.h"
#import "JZStepListModel.h"
#import "JZClassListModel.h"
#import "JrdNodeModel.h"
#import "JrdCourseNodeCellTableViewCell.h"
#import "AudioPlayerController.h"
#import "Reachability.h"
@interface JrdChapterNodeViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray* nodeListArray;
    NSInteger vHeadIndex;
    JZCourseDetailModel *_jzCourseDM;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) NSMutableArray *songArray;
@end

@implementation JrdChapterNodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated{
    self.sc_navigationItem.title = _chaptermodel.ChapterName;//NSLocalizedString(@"v2_my_study",nil);//@"我们学习";
}

- (void)loadView{
    [super loadView];
    [self configureNav];
    [self initData];
    [self initTableView];
    [self dataJson];
}

- (void)initData{
    nodeListArray = [[NSMutableArray alloc] init];
    vHeadIndex = 0;
}

- (void)initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-44) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    [self setupTableview];
}

- (void)setupTableview{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; ++i) {
        UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [idleImages addObject:image];
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    //设置即将刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
    [refreshingImages addObject:image1];
    UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
    [refreshingImages addObject:image2];
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    //马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
}


- (void)loadNewData{
    //end refersh because use fake data
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseChapterData];
    });
}

- (void)getCourseChapterData{
}


- (void)configureNav{
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_back"] highlight:[UIImage imageNamed:@"btn-back-normal"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return nodeListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        static NSString *cellIndentifier = @"detailCell11";
        
        JrdCourseNodeCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[JrdCourseNodeCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
            //下划线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(40, 63.5, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView];
        }
        JrdNodeModel* chapterModel = nodeListArray[indexPath.row];
        [cell setJzClassM:chapterModel];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIButton* image= [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 36, 22, 20, 20)];
        [image setBackgroundImage:[UIImage imageNamed:@"ico_download"] forState:UIControlStateNormal];
        [image addTarget:self action:@selector(downloadClick) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = image;
        return cell;
}

- (void)downloadClick{
    NSLog(@"zlwu download click");
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"下载错误" message:@"此课件暂不支持下载" delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
    [alert show];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(0 == section){
        return NSLocalizedString(@"jrd_course_des", nil);//@"课程简介";
    }else{
        return NSLocalizedString(@"jrd_chapter", nil);//@"科目";
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"zlwu add for select index");
            //判断，如果处于 仅wifi下播放，且当前状态不是wifi状态下，弹出警告框
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"vDownloadUnderWifi"] == YES){
            NSString* currentState =  [self GetCurrntNet];
            if(nil == currentState){
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_nowifi_title", nil) message:NSLocalizedString(@"jrd_nowifi_message", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
                alertView.frame  = CGRectMake((SCREEN_WIDTH - 200)/2, (SCREEN_HEIGHT - 150)/2, 200, 100);
                alertView.tag = 0;
                [alertView show];
            }else if([currentState isEqualToString:@"wifi"]){
                AudioPlayerController *audio = [AudioPlayerController audioPlayerController];
                [audio initWithArray:self.songArray index:indexPath.row];
                [self presentViewController:audio animated:YES completion:nil];
            }else{
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_nowifi_title", nil) message:NSLocalizedString(@"jrd_nowifi_message", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
                alertView.frame  = CGRectMake((SCREEN_WIDTH - 200)/2, (SCREEN_HEIGHT - 150)/2, 200, 100);
                alertView.tag = 0;
                [alertView show];
            }
        }else{
            AudioPlayerController *audio = [AudioPlayerController audioPlayerController];
            [audio initWithArray:self.songArray index:indexPath.row];
            [self presentViewController:audio animated:YES completion:nil];
            
        }
}

- (NSMutableArray *)songArray
{
    if (!_songArray) {
        _songArray = [NSMutableArray array];
    }
    return _songArray;
}


-(void)dataJson
{
    NSString *str = [[NSBundle mainBundle]pathForResource:@"musicPaper" ofType:@"json"];
    NSData *data = [[NSData alloc]initWithContentsOfFile:str];
    
    NSMutableArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@,  ---%ld",dataArray, (unsigned long)dataArray.count);
    //    [self.songArray addObject:dic];
    for (NSDictionary *dic in dataArray) {
        MusicModel *model = [[MusicModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.songArray addObject:model];
    }
    //[self.songTableView reloadData];
}

-(NSString*)GetCurrntNet
{
    NSString* result;
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:// 没有网络连接
            result=nil;
            break;
            
        case ReachableViaWWAN:// 使用3G网络
            result=@"3g";
            break;
            
        case ReachableViaWiFi:// 使用WiFi网络
            result=@"wifi";
            break;
    }
    return result;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
